package com.sanji.sjmallmodule.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.main.MainActivity;
import com.sanji.sjmallmodule.permission.PermissionsActivity;
import com.sanji.sjmallutils.DownloadService;
import com.sanji.sjmallutils.PermissionsChecker;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallconfig.ConfigConts.ERRORMSG;
import static com.sanji.sjmallconfig.ConfigConts.STATUS_ERROR;
import static com.sanji.sjmallconfig.ConfigConts.STATUS_STRING;
import static com.sanji.sjmallconfig.ConfigConts.STATUS_SUCCESS;


/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, NoHttpListener {

    @BindView(R.id.login_image)
    ImageView logoImg;
    @BindView(R.id.login_register)
    TextView loginRegister;
    @BindView(R.id.login_remember_pass)
    CheckBox isRememberBox;//是否记住密码
    @BindView(R.id.login_shop_name)
    EditText loginShopName;
    @BindView(R.id.login_pass_word)
    EditText loginPassWord;
    @BindView(R.id.loginBtn)
    Button loginBtn;
    @BindView(R.id.login_eyes)
    CheckBox loginEyes;
    @BindView(R.id.login_forget_password)
    TextView forgetPassword;
    Request<JSONObject> request;
    @BindView(R.id.version_name)
    TextView versionName;
    private String userId;
    private String userName;
    private String account;
    private String passWord;
    private String idCard;//身份证号
    private String addressStr;//地址

    private PackageManager mPackageMager = null;
    private PackageInfo mPackageInfo = null;
    private AlertDialog.Builder mVersionDialog;
    private String versUrl = "";
    private AlertDialog.Builder showInfoDialog;//提示信息
    private int blackCode;
    private String loginUrl;

    //权限检测器
    private PermissionsChecker mPermissionsChecker;
    private static final int REQUEST_CODE = 0; // 请求码
    private String updateFlag = null;//0-不强制升级，1-强制升级

    //用于判断连续点击
    private long firstTime = 0;
    private long interval = 1000;
    private int clickCount = 0;
    private TimerTask task;
    private Timer delayTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();
        isPasswordShowListener();

        mPermissionsChecker = new PermissionsChecker(this);

        try {
            mPackageMager = this.getPackageManager();
            mPackageInfo = mPackageMager.getPackageInfo(this.getPackageName(), 0);
            versionName.setText("V" + mPackageInfo.versionName);
        } catch (Exception e) {

        }
        loginUrl = myShare.getString("BASE_URL", ConfigAPI.BASE_URL)+ "login/check";

        getVersion();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //缺少权限时，进入权限配置页面
        if (mPermissionsChecker.lacksPermission(ConfigConts.PERMISSION_EXTERNAL_STORAGE)) {
            PermissionsActivity.startActivityForResult(this, REQUEST_CODE, ConfigConts.PERMISSION_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSION_DENIED){
            finishActivity();
        }
    }

    /**
     * 数据的初始化
     */
    public void initView() {
        loginRegister.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        forgetPassword.setOnClickListener(this);
        loginShopName.setText(myShare.getString(ConfigConts.ACCOUNT, ""));
        isRememberBox.setOnClickListener(this);
        logoImg.setOnClickListener(this);
        //记录是否记住密码
        boolean isRemPwd = myShare.getBoolean(ConfigConts.IS_REMERBER, false);
        if (isRemPwd) {
            loginPassWord.setText(myShare.getString(ConfigConts.USER_PASSWORD, ""));
            isRememberBox.setChecked(true);
        } else {
            isRememberBox.setChecked(false);
        }
        blackCode = getIntent().getIntExtra("blackCode", 0);
        if (blackCode == 1) {
            showInfoDialog(getString(R.string.login_black_toast));
        }
    }

    /**
     * 判断当前是否需要显示密码
     */
    public void isPasswordShowListener() {
        loginEyes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                int passwordLength = loginPassWord.getText().length();
                loginPassWord.setInputType(b ? (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) :
                        (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
                loginPassWord.setSelection(passwordLength);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_register:
                intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.loginBtn:
                loginPressed();
                break;
            case R.id.login_forget_password:
                //忘记密码
                intent = new Intent(this, ResetPasswordActivity.class);
                intent.putExtra("enteType", 0);
                startActivity(intent);
                break;
            case R.id.login_remember_pass:
                boolean bol = myShare.getBoolean(ConfigConts.IS_REMERBER, false);
                myShare.put(ConfigConts.IS_REMERBER, !bol);
                break;
            case R.id.login_image:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime < interval){
                    ++clickCount;
                }else{
                    clickCount = 1;
                }
                //延迟，用于判断用户的点击操作是否结束
                delay();
                firstTime = secondTime;

                break;
        }
    }

    //延迟时间是连击的时间间隔有效范围
    private void delay(){
        if(task != null){
            task.cancel();
        }

        task = new TimerTask() {

            @Override
            public void run() {
                Message message = new Message();
                handler.sendMessage(message);
            }
        };
        delayTimer = new Timer();
        delayTimer.schedule(task, interval);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(clickCount == 6){
                intent = new Intent(mCtx,UrlEditActivity.class);
                startActivity(intent);
            }
            delayTimer.cancel();
            clickCount = 0;

            super.handleMessage(msg);
        }
    };
    /**
     * 点击登录时
     */
    public void loginPressed() {
        String name = loginShopName.getText().toString();
        passWord = loginPassWord.getText().toString();
        if (TextUtils.isEmpty(name)) {
            Tools.toastTools(mCtx, getString(R.string.login_phone_null));
            return;
        }
        myShare.put(ConfigConts.ACCOUNT, name);
        if (!Tools.isPhoneNumber(name)) {
            Tools.toastTools(mCtx, getString(R.string.login_input_phone));
            return;
        }
        if (TextUtils.isEmpty(passWord) || passWord.trim().length() < 6) {
            Tools.toastTools(mCtx, getString(R.string.login_input_pwd));
            return;
        }
        loginUrl = myShare.getString("BASE_URL", ConfigAPI.BASE_URL)+ "login/check";
        request = NoHttp.createJsonObjectRequest(loginUrl, RequestMethod.POST);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username", name);
            jsonObject.put("password", passWord);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setDefineRequestBodyForJson(jsonObject);
        //设置取消标志
        request.setCancelSign(loginUrl.hashCode());
        //发送登录请求
        NoHttpCallBack.getInstance().add(mCtx, loginUrl.hashCode(), request, this, true, true);
    }

    /**
     * 成功时的回调
     */
    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject object = (JSONObject) response.get();
        String status = object.optString(STATUS_STRING);
        if (what == loginUrl.hashCode()) {
            if (status.equals(STATUS_SUCCESS)) {
                JSONObject json = object.optJSONObject("result");
                userId = json.optString("id");
                userName = json.optString("username");
                String trueName = json.optString("truename");
                String provinceId = json.optString("province");//省
                String cityId = json.optString("city");//市
                String areaId = json.optString("area");//区
                String addressStr = json.optString("address");//详细地址
                String mobile = json.optString("mobile");
                String zip = json.optString("zip");//邮编
                String regionStr = json.optString("region");//省市县街道
                myShare.put(ConfigConts.PROVINCIAL_ID, provinceId);
                myShare.put(ConfigConts.CITY_ID, cityId);
                myShare.put(ConfigConts.REGION, regionStr);
                myShare.put(ConfigConts.AREA_ID, areaId);
                myShare.put(ConfigConts.ADDRESS_STR, addressStr);
                myShare.put(ConfigConts.USER_ID, userId);
                myShare.put(ConfigConts.TRUE_NAME, trueName);
                myShare.put(ConfigConts.USER_NAME, userName);
                myShare.put(ConfigConts.ZIP, zip);
                myShare.put(ConfigConts.USER_PASSWORD, passWord);
                myShare.put(ConfigConts.MOBILE, mobile);
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finishActivity();
            } else {
                String errorCode = object.optString("errorCode");
                String errorMsg = object.optString(ERRORMSG);
                if (errorCode.equals("unPaided")) {
                    //黑名单提示
                    showInfoDialog(errorMsg);
                } else {
                    Tools.toastTools(mCtx, errorMsg);
                }
            }
        } else if (what == ConfigAPI.VERSION_LASTEST_URL.hashCode()) {
            if (status.equals(STATUS_SUCCESS)) {
                JSONObject json = object.optJSONObject("result");
                int versCode = json.optInt("versionCode");
                int localCode = mPackageInfo.versionCode;
                String versName = json.optString("versionName");
                String remark = json.optString("remark");
                updateFlag = json.optString("updateFlag");
                if (versCode > localCode) {
                    versUrl = json.optString("url");
                    versionDialog(versName, remark, updateFlag);
                }
            } else if (status.equals(STATUS_ERROR)) {
                String errorMsg = object.optString(ERRORMSG);
                Tools.toastTools(mCtx, errorMsg);
            }
        }
    }

    /**
     * 失败时的回调
     */
    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(mCtx, getString(R.string.request_false));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (null != request) {
//            request.cancel();
//        }
        NoHttpCallBack.getInstance().getRequestQueue().cancelBySign(ConfigAPI.LOGIN_URL.hashCode());
    }

    /**
     * 获取服务端最新版本信息
     */
    private void getVersion() {
        String versionUrl = ConfigAPI.VERSION_LASTEST_URL;
        request = NoHttp.createJsonObjectRequest(versionUrl, RequestMethod.GET);
        //设置取消标志
        request.setCancelSign(ConfigAPI.VERSION_LASTEST_URL.hashCode());
        //发送登录请求
        NoHttpCallBack.getInstance().add(mCtx, ConfigAPI.VERSION_LASTEST_URL.hashCode(), request, this, true, true);
    }

    /**
     * 版本更新dialog
     *
     * @param versName
     * @param remark
     */
    private void versionDialog(String versName, String remark, final String updateFlag) {
        if (mVersionDialog == null) {
            mVersionDialog = new AlertDialog.Builder(mCtx);
            mVersionDialog.setTitle(getString(R.string.login_version_update_title));
            mVersionDialog.setMessage(String.format(getString(R.string.login_version_update_message),versName,remark));
//            mVersionDialog.setMessage("版本号：" + versName + "\n" + "更新内容：" + remark);
            if (updateFlag.equals("1")) {
                mVersionDialog.setPositiveButton(getString(R.string.login_version_update_positive), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(mCtx, DownloadService.class);
                        intent.putExtra("apkUrl", versUrl);
                        startService(intent);
                        dialogInterface.dismiss();
                    }
                });
            } else {
                mVersionDialog.setPositiveButton(getString(R.string.login_version_update_positive), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(mCtx, DownloadService.class);
                        intent.putExtra("apkUrl", versUrl);
                        startService(intent);
                        dialogInterface.dismiss();
                    }
                }).setNegativeButton(getString(R.string.title_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            }
            mVersionDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    if (updateFlag.equals("1")) {
                        finish();
                    }
                }
            });
            mVersionDialog.create();
        }
//            mVersionDialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialogInterface, int i) {
//                    Intent intent = new Intent(mCtx, DownloadService.class);
//                    intent.putExtra("apkUrl", versUrl);
//                    startService(intent);
//                    dialogInterface.dismiss();
//                }
//            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialogInterface, int i) {
//                    dialogInterface.dismiss();
//                }
//            });
//            mVersionDialog.create();
//        }
        mVersionDialog.show();
    }

    /**
     * 提醒付款的提示
     */
    private void showInfoDialog(String info) {
        if (showInfoDialog == null) {
            showInfoDialog = new AlertDialog.Builder(this);
            showInfoDialog.setTitle(getString(R.string.login_version_update_toast)).setMessage(info);
            showInfoDialog.setPositiveButton(getString(R.string.title_sure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            showInfoDialog.create();
            showInfoDialog.setCancelable(false);
        }
        showInfoDialog.show();
    }
}
